import Vue from 'vue'
import {
  HOME_CASUAL,
  HOME_NAV,
  GOODS_LIST,
  RECOMMEND_LIST,
  SEARCH_LIST,
  USER_INFO,
  RESET_USER_INFO,
  SHOP_CART,
  ADD_GOODS_COUNT,
  REDUCE_GOODS_COUNT,
  SELECT_ALL,
  SELECT,
  DELETE_SINGLE
} from './mutation-type'

export default {
  /*
  *   这种定义函数的方式可以理解为es6的新语法，使用时按正常函数使用就行了
  * */
  [HOME_CASUAL](state, {homecasual}){
    state.homecasual = homecasual
  },
  [HOME_NAV](state, {homenav}){
    state.homenav = homenav;
  },
  [GOODS_LIST](state,{goodslist}){
    state.goodslist = goodslist;
  },
  [RECOMMEND_LIST](state,{recommendlist}){
    // 通过数组拼接实现下拉加载更多
    state.recommendlist = state.recommendlist.concat(recommendlist);
  },
  [SEARCH_LIST](state,{searchlist}){
    state.searchlist = searchlist;
  },
  [USER_INFO](state,{userInfo}){
    state.userInfo = userInfo;
  },
  [RESET_USER_INFO](state){
    state.userInfo = {};
  },
  [SHOP_CART](state,{shopCart}){
    state.shopCart = shopCart;
  },
  [ADD_GOODS_COUNT](state,{goods}){
    // 因为goods本身就是从shopCart中获取的，所以指向的浏览器内存地址是同一块
    goods.buy_count++;

  },
  [REDUCE_GOODS_COUNT](state,{goods}){
    if(goods.buy_count){
      goods.buy_count--;
      if(goods.buy_count === 0){
        // 这里当商品数量减到0时直接删除商品
        const index = state.shopCart.indexOf(goods);
        state.shopCart.splice(index,1);
      }
    }
  },
  [SELECT_ALL](state,{isSelect}){
    state.shopCart.forEach((goods,index)=>{
      if(goods.checked){ // 该属性存在
        goods.checked = !isSelect;
      }else {
        Vue.set(goods,'checked',!isSelect);
      }
    })
  },
  [SELECT](state,{goods}){
    // 页面购物车列表中的数据就是从state中获取的，所以指向同一片浏览器内存空间
    if(goods.checked){
      goods.checked = !goods.checked;
    }else {
      Vue.set(goods,'checked',!goods.checked)
    }
  },
  [DELETE_SINGLE](state,{goods}){
    const index = state.shopCart.indexOf(goods);
    state.shopCart.splice(index,1);
  }
}
